package com.tsingteng.cosfun.ui.message.uploadreportfragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.qiniu.pili.droid.shortvideo.PLShortVideoUploader;
import com.qiniu.pili.droid.shortvideo.PLUploadResultListener;
import com.qiniu.pili.droid.shortvideo.PLUploadSetting;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.app.AppContext;
import com.tsingteng.cosfun.base.BasePresenterActivity;
import com.tsingteng.cosfun.bean.UploadReportBean;
import com.tsingteng.cosfun.bean.VideoSignBean;
import com.tsingteng.cosfun.helper.VideoHelper;
import com.tsingteng.cosfun.utils.FileUtils;
import com.tsingteng.cosfun.utils.ImageUtils;
import com.tsingteng.cosfun.utils.ImageViewUtils;
import com.tsingteng.cosfun.utils.KeyBoardUtils;
import com.tsingteng.cosfun.utils.LogUtils;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.widget.TitleView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;


/**
 * 上传举报原因页面
 * 常胜
 * 2018.8.21
 */
public class UploadReportActivity extends BasePresenterActivity<UploadReportPresenter, UploadReportContract.IUploadReportView> implements UploadReportContract.IUploadReportView, View.OnClickListener, PLUploadResultListener ,TextWatcher{

    @BindView(R.id.et_why_report)
    TextView etWhyReport;
    @BindView(R.id.tv_report)
    TitleView tvReport;
    @BindView(R.id.btn_commit)
    Button btnCommit;
    @BindView(R.id.et_report_describe)
    EditText etReportDescribe;
    @BindView(R.id.ll_report_camera)
    LinearLayout llReportCamera;
    @BindView(R.id.tv_why_report)
    TextView tvWhyReport;
    @BindView(R.id.ll_report)
    LinearLayout llReport;
    @BindView(R.id.tv_report_describe)
    TextView tvReportDescribe;
    @BindView(R.id.rv_rv)
    RecyclerView mRv;
    @BindView(R.id.tv_report_number)
    TextView mTvReportNumber;
    @BindView(R.id.tv_remind)
    TextView tvRemind;
    @BindView(R.id.ll_report_link)
    LinearLayout llReportLink;
    @BindView(R.id.tv_report_yin_si)
    TextView tvYinSi;
    @BindView(R.id.ll_all_report)
    RelativeLayout llAllReport;
    @BindView(R.id.ll_report_link_new)
    LinearLayout llAllReportNew;
    private String picPath = null;
    public static final int PHOTOZOOM = 2; // 缩放
    public static final int PHOTORESOULT = 3;// 结果
    public static final String IMAGE_UNSPECIFIED = "image/*";
    private int type;
    private String whyReportContent;
    private String path;
    private String domain;
    private String sign;
    private PLShortVideoUploader mVideoUploadManager;
    private List<String> picList = new ArrayList<>();
    private UpLoadReportAdapter upLoadReportAdapter;
    private int count = 0;
    private List<String> urlPic = new ArrayList<>();
    private int workId;
    private static Handler handler = new Handler();
    private int whyReportId;
    private String whyReportMessage;
    private Bundle bundle;
    private int index = 0;





    @Override
    protected void initData() {
        ininBundle();
        for (int i = 0; i < 5; i++) {
            urlPic.add("");
        }
        mRv.setLayoutManager(new GridLayoutManager(this, 4, LinearLayoutManager.VERTICAL, false));
        upLoadReportAdapter = new UpLoadReportAdapter();
        mRv.setAdapter(upLoadReportAdapter);
        PLUploadSetting uploadSetting = new PLUploadSetting();
        mVideoUploadManager = new PLShortVideoUploader(AppContext.getContext(), uploadSetting);
        mVideoUploadManager.setUploadResultListener(this);
        etWhyReport.setText(whyReportMessage);
        etReportDescribe.addTextChangedListener(this);
        //初始化头部信息
        initTitleView();
        KeyBoardUtils.observeSoftKeyboard(this, new KeyBoardUtils.OnSoftKeyboardChangeListener() {
            @Override
            public void onSoftKeyBoardChange(int softKeybardHeight, boolean visible) {
                if (visible) {
                    if (tvRemind == null || btnCommit == null) return;
                    tvRemind.setVisibility(View.GONE);
                    btnCommit.setVisibility(View.GONE);
                } else {
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (tvRemind == null || btnCommit == null) return;
                            tvRemind.setVisibility(View.VISIBLE);
                            btnCommit.setVisibility(View.VISIBLE);
                        }
                    }, 100);

                }
            }
        });

        btnCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (0 == index) {
                    index = 1;
                    whyReportContent = etReportDescribe.getText().toString();
                    if (picList == null || picList.size() == 0) {
                        mPresenter.loginUploadReport(String.valueOf(whyReportId), Long.valueOf(workId), type, whyReportContent, urlPic.get(0), urlPic.get(1), urlPic.get(2), urlPic.get(3));
                    } else {
                        mPresenter.loginUploadSeven();
                    }
                }
            }
        });
        //图片上传
        llReportCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ImageViewUtils.starPhoto(UploadReportActivity.this,false);
            }
        });
    }

    private void ininBundle() {

        if (whyReportId == 5) {//5盗用   //8 请饭营私
            llReportLink.setVisibility(View.VISIBLE);
            llAllReportNew.setVisibility(View.VISIBLE);
        } else if (whyReportId == 8) {
            llAllReport.setVisibility(View.GONE);
            llAllReportNew.setVisibility(View.GONE);
            tvYinSi.setVisibility(View.VISIBLE);
            tvYinSi.setText(getResources().getString(R.string.reprot_ying_si_1) + "\n" + "\n" +
                    getResources().getString(R.string.reprot_ying_si_2) + "\n" +
                    getResources().getString(R.string.reprot_ying_si_3) + "\n" +
                    getResources().getString(R.string.reprot_ying_si_4) + "\n" +
                    getResources().getString(R.string.reprot_ying_si_5) + "\n" + "\n" +
                    getResources().getString(R.string.reprot_ying_si_6));
        }
    }

    private void initTitleView() {
        switch (type) {
            case 1:
                tvReport.setTitle("视频举报");
                break;
            case 2:
                tvReport.setTitle("用户举报");
                break;
            case 3:
                tvReport.setTitle("评论举报");
                break;
            case 4:
                tvReport.setTitle("私信举报");
                break;
            case 5:
                tvReport.setTitle("便当举报");
                break;
            case 6:
                tvReport.setTitle("尬评举报");
                break;
        }
        tvReport.setIvLeft(R.drawable.back_big_icon);
        tvReport.setOnTitleClickListener(new TitleView.OnTitleClickListener() {
            @Override
            public void onLeft() {
                finish();
            }

            @Override
            public void onRight() {

            }

            @Override
            public void onRight2() {

            }
        });
    }



    @Override
    protected UploadReportPresenter createPresenter() {
        return new UploadReportPresenter();
    }




    @Override
    protected int getLayoutId() {
        return R.layout.fragment_report;
    }

    @Override
    protected void getIntentData(Intent intent) {
        whyReportMessage = intent.getStringExtra("whyReportMessage");
        whyReportId = intent.getIntExtra("whyReportId", -1);
        type = intent.getIntExtra("type", -1);
        workId = intent.getIntExtra("workId", -1);
    }

    @Override
    public void showUploadReportResult(UploadReportBean str) {
        int status = str.getStatus();
        if (status == 1) {
            showToast("举报成功!");
           finish();
            VideoHelper.getIntence().getFragment().finish();
            VideoHelper.getIntence().setFragment(null);
        } else {
            showToast("未能成功举报！");
        }
    }

    @Override
    public void showUploadSeven(VideoSignBean videoSignBean) {
        path = videoSignBean.getPath();
        domain = videoSignBean.getDomain();
        sign = videoSignBean.getSign();
//        if (arrString[0] != null){
//            mVideoUploadManager.startUpload( joinCostarBean.getVideoUrl(), String.valueOf(LogonUtils.getProFildId()+System.currentTimeMillis()).hashCode()+upPath,upSign);
//
//        }
        try {
            FileInputStream fileInputStream = new FileInputStream(picList.get(0));
            String fileName = FileUtils.getFileMD5(fileInputStream);
            mVideoUploadManager.startUpload(picList.get(0), path + "/" + fileName + ".jpg", sign);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


        LogUtils.i("0000000000000000" + String.valueOf(LogonUtils.getProFildId() + System.currentTimeMillis()).hashCode());
//
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String imagePath;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    LocalMedia localMedia = selectList.get(0);
                    if (localMedia.isCut()) {
                        imagePath = localMedia.getCutPath();
                    } else if (localMedia.isCompressed()) {
                        imagePath = localMedia.getCompressPath();
                    } else {
                        imagePath = localMedia.getPath();
                    }
                    picList.add(imagePath);
                    resetView();
                    break;
            }
        }
    }

    public void resetView() {
        mTvReportNumber.setText(picList.size() + "/4");
        upLoadReportAdapter.getData().clear();
        upLoadReportAdapter.addData(picList);
        upLoadReportAdapter.notifyDataSetChanged();
        llReportCamera.setVisibility(picList.size() == 4 ? View.GONE : View.VISIBLE);

    }

    @Override
    public void onClick(View view) {

    }

    @Override
    public void onUploadVideoSuccess(JSONObject jsonObject) {
        //上传成功
        try {
            final String filePath = domain + "/" + jsonObject.getString("key");
            LogUtils.i(filePath + "0000000000000000");
            urlPic.set(count, filePath);
            count++;
            if (count > picList.size() - 1) {
                //说明已经上传完成
                mPresenter.loginUploadReport(String.valueOf(whyReportId), Long.valueOf(workId), type, whyReportContent, urlPic.get(0), urlPic.get(1), urlPic.get(2), urlPic.get(3));
                return;
            }
            FileInputStream fileInputStream = null;

            fileInputStream = new FileInputStream(picList.get(count));
            String fileName = FileUtils.getFileMD5(fileInputStream);
            mVideoUploadManager.startUpload(picList.get(count), path + "/" + fileName + ".jpg", sign);
//            mVideoUploadManager.startUpload(picList.get(count), path + "/" + String.valueOf(LogonUtils.getProFildId() + System.currentTimeMillis()).hashCode(), sign);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onUploadVideoFailed(int i, String s) {

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String etString=etReportDescribe.getText().toString().trim();
        if (etString.length() == 200) {
//            WarningDialog warningDialog = new WarningDialog(this);
//            warningDialog.show();
//            new Handler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    warningDialog.dissMiss();
//                }
//            }, 1500);
            Toast.makeText(UploadReportActivity.this,getResources().getString(R.string.message_limit),Toast.LENGTH_LONG).show();
        }
    }

    public class UpLoadReportAdapter extends BaseQuickAdapter<String, BaseViewHolder> {
        public UpLoadReportAdapter() {
            super(R.layout.item_upload_report_adapter);
        }

        @Override
        protected void convert(BaseViewHolder helper, String item) {
            ImageView imageView = helper.getView(R.id.iv_report_third);
            ImageUtils.LoadImage(mContext, item, imageView);
            helper.getView(R.id.delete_image_view_third).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    picList.remove(item);
                    resetView();
                }
            });
        }
    }


}
